<template>
  <n-drawer
    v-model:show="isDrawer"
    :width="width"
    :placement="placement"
    :auto-focus="false"
    @after-leave="handleReset"
  >
    <n-drawer-content :title="title" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
      >
        <n-form-item label="上级区域" path="parent_id">
          <n-tree-select
            label-field="region_name"
            value-field="id"
            key-field="id"
            :options="getRegionTreeList"
            clearable
            v-model:value="formParams.parent_id"
            placeholder="请选择区域，省份无需选择"
          />
        </n-form-item>

        <n-form-item label="区域名称" path="region_name">
          <n-input placeholder="请输入区域名称" v-model:value="formParams.region_name" />
        </n-form-item>

        <n-form-item label="区域编码" path="region_code">
          <n-input placeholder="请输入区域编码" v-model:value="formParams.region_code" />
        </n-form-item>

        <n-form-item label="显示排序" path="region_orders">
          <n-input-number
            placeholder="显示排序"
            v-model:value="formParams.region_orders"
            class="w-full"
          />
        </n-form-item>

        <n-grid x-gap="12" :cols="2">
          <n-gi>
            <n-form-item label="是否省份" path="is_province">
              <n-switch v-model:value="formParams.is_province" />
            </n-form-item>
          </n-gi>

          <n-gi>
            <n-form-item label="是否城市" path="is_city">
              <n-switch v-model:value="formParams.is_city" />
            </n-form-item>
          </n-gi>
        </n-grid>

        <n-grid x-gap="12" :cols="2">
          <n-gi>
            <n-form-item label="是否区县" path="is_district">
              <n-switch v-model:value="formParams.is_district" />
            </n-form-item>
          </n-gi>

          <n-gi>
            <n-form-item label="是否启用" path="is_enable">
              <n-switch v-model:value="formParams.is_enable" />
            </n-form-item>
          </n-gi>
        </n-grid>
      </n-form>

      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { useMessage } from 'naive-ui';
  import type { formParamsType } from './types';

  import { addRegion, editRegion, regionInfo } from '@/api/system/region';

  const rules = {
    region_name: {
      required: true,
      message: '区域名称不能为空',
      trigger: 'blur',
    },
    region_code: {
      required: true,
      message: '区域编码不能为空',
      trigger: 'blur',
    },
  };

  const emit = defineEmits(['change']);

  const props = defineProps({
    title: {
      type: String,
      default: '添加区域',
    },
    width: {
      type: Number,
      default: 380,
    },
    regionList: {
      type: Array,
    },
  });

  const getRegionTreeList = computed(() => {
    return props.regionList;
  });

  const defaultValueRef = () => ({
    id: null,
    region_name: '',
    region_code: '',
    is_center_city: false,
    is_province: false,
    is_city: false,
    is_district: false,
    is_enable: true,
    parent_id: null,
    region_orders: null,
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);

  const formParams = ref<formParamsType>(defaultValueRef());

  const placement = 'right';

  function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      getInfo();
      return;
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        if (formParams.value.id) {
          editRegion(formParams.value).then((_) => {
            message.success('编辑成功');
            emit('change');
            handleReset();
            closeDrawer();
          });
        } else {
          addRegion(formParams.value).then((_) => {
            message.success('添加成功');
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    regionInfo({ id: formParams.value.id }).then((res) => {
      const info = {
        id: res.id,
        is_center_city: res.is_center_city,
        is_province: res.is_province,
        is_city: res.is_city,
        is_district: res.is_district,
        is_enable: res.is_enable,
        parent_id: res.parent_id,
        region_code: res.region_code,
        region_name: res.region_name,
        region_orders: res.region_orders,
      };
      formParams.value = info;
      isDrawer.value = true;
    });
  }

  onMounted(() => {});

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
